import Cookie from 'js-cookie';
import StorageUtil from './storage';
import { getConfig } from '@/utils/config';

export const config = getConfig();
/**
 * 创建一个普通单键对象
 * @param key
 * @param value
 */
export function createObject(key: string, value: any) {
  const o: Record<string, any> = {};
  o[key] = value;
  return o;
}

/**
 * 判断是否为一个有效字符串
 * @param value
 */
export function isValidString(value: any) {
  return value && value.trim() !== '';
}

/**
 * 保存Token
 * @param data
 */
export function saveToken(data: { token: string; expire: number }) {
  const { token, expire } = data;
  Cookie.set(config.ID_KEY, token, {
    expires: new Date(Date.now() + expire * 1000),
    domain: `.${getConfig('domain')}`,
    path: '/',
  });
  StorageUtil.save(config.TOKEN_KEY, token);
  StorageUtil.save(config.META_KEY, JSON.stringify({ time: Date.now(), expire }));
}

/**
 * 获取TOKEN
 */
export function getToken() {
  return Cookie.get(config.ID_KEY);
  // return StorageUtil.get(config.TOKEN_KEY);
}

/**
 * 清除TOKEN
 */
export function clearToken() {
  Cookie.remove(config.ID_KEY, {
    domain: `.${getConfig('domain')}`,
  });
  StorageUtil.remove(config.TOKEN_KEY);
  StorageUtil.remove(config.META_KEY);
}

/**
 * 从存储判断是否登录过期
 */
export function isLogin() {
  const meta = StorageUtil.get(config.META_KEY);
  if (!StorageUtil.get(config.TOKEN_KEY) || !meta) {
    return false;
  }
  const { time, expire } = meta;
  if (time + expire * 1000 < Date.now()) {
    clearToken();
    return false;
  }
  return true;
}

export function checkAuth() {
  return isLogin();
}

/**
 * 获取SVG ICON
 * @param name
 * @param className
 */
export function getIcon(name: string, className = 'svg-icon') {
  return `<svg class="${className}"><use xlink:href="#${name}"></use></svg>`;
}

/**
 * path 是否可通过
 * @param path
 * @param paths
 */
export function isPathAllow(path: string, paths: string[] = []) {
  return paths.some((item) => {
    if (/^[\/\w]+$/.test(item)) {
      return item === path;
    }
    const reg = new RegExp(item, 'i');
    return reg.test(path);
  });
}

/**
 * 获取根路径
 */
export function getRootPath() {
  const location = window.location;
  const protocol = location.protocol;
  const host = location.host;
  return `${protocol}//${host}`;
}

/**
 * 获取相对于根路径
 * @param path
 */
export function getPathFromRoot(path: string) {
  return `${getRootPath()}` + (path[0] === '/' ? path : `/${path}`);
}

export function openWindow(url: string, name: string, iWidth: number, iHeight: number) {
  if (typeof window === 'undefined') {
    return null;
  }
  const iTop = (window.screen.availHeight - 30 - iHeight) / 2; //获得窗口的垂直位置;
  const iLeft = (window.screen.availWidth - 10 - iWidth) / 2; //获得窗口的水平位置;
  return window.open(
    url,
    name,
    'height=' +
      iHeight +
      ',width=' +
      iWidth +
      ',top=' +
      iTop +
      ',left=' +
      iLeft +
      ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no'
  );
}
